const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const upload = require("multer")({ dest: "uploads/" });
const path = require("path");
const fs = require("fs");
let newData;
let usernameList;
readData();
function readData() {
  fs.readFile("./data.json", "utf8", (err, readData) => {
    newData = JSON.parse(readData);
    usernameList = newData.user.map((item) => item.username);
  });
}
const allowCors = function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  res.header("Access-Control-Allow-Credentials", "true");
  next();
};
app.use(allowCors);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static("uploads"));
app.post("/login", (req, res) => {
  if (req.body) {
    const { user, pw } = req.body;
    const userList = newData.user;
    for (const item of userList) {
      if (user === item.username && pw == item.password) {
        res.send({ code: 1, msg: "登录成功" });
        return false;
      }
    }
    res.send({ code: 0, msg: "失败" });
  }
});

app.post("/register", (req, res) => {
  if (req.body) {
    if (usernameList.includes(req.body.user)) {
      res.send({ code: 0, msg: "用户名存在" });
    } else {
      newData.user.push(req.body);
      fs.writeFile("./data.json", JSON.stringify(newData), (err) => {
        readData();
      });
      res.send({ code: 1, msg: "注册成功" });
    }
  }
});

app.post("/upload", upload.any(), (req, res) => {
  const des_file = "./uploads/" + req.files[0].originalname;
  fs.readFile(req.files[0].path, function (err, data) {
    fs.writeFile(des_file, data, function (err) {
      if (err) {
        console.log(err);
      } else {
        const imgPath = `http://127.0.0.1:8090/${req.files[0].originalname}`;
        const response = {
          message: "上传成功",
          filename: imgPath,
        };
        if (!newData.imgPath.includes(imgPath)) {
          newData.imgPath.push(imgPath);
          fs.writeFile("./data.json", JSON.stringify(newData), (err) => {
            readData();
          });
        }
        fs.unlink(req.files[0].path, (err) => {});
        res.end(JSON.stringify(response));
      }
    });
  });
});

app.get("/get", (req, res) => {
  if (req.query) {
    const { id } = req.query;
    if (id >= 0 && id <= 3) {
      res.send({ code: 1, msg: `你传入了${id}` });
    } else {
      res.send({ code: 0, msg: "请传入0-3之间的数" });
    }
  }
});

app.get("/getData", (req, res) => {
  res.send(newData.data);
});

app.listen(8090, function () {
  console.log("运行在8090端口");
});
